package com.tank.elk.elasticsearch;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/10/25 0025
 * Time: 下午 8:37
 * To change this template use File | Settings | File Templates.
 */
@Slf4j
public class Es5Highlight {

    public static void main(String[] args) throws UnknownHostException {
        try {
           // String index = "logstash-";
            String index = "applog-2017.10.27";
            String path = "/data/log/aggregate.log";
            //获取日志ID
            SearchResponse response = search(index, "20171027112046011331143046543895",path,1);
            //获取查询结果集
            SearchHits searchHits = response.getHits();
            log.info("按订单号和日志日期查询共匹配到记录条目:{}",searchHits.totalHits());
            if (searchHits.getTotalHits()==0){
                log.warn("未匹配到日志");
            }
            Map<String,Object> logDetail = searchHits.getAt(0).getSource();
            String traceLogId = getTraceLogId(logDetail.get("message").toString());
            //按日志ID查询所有日志
            response = search(index, traceLogId,null,(int)searchHits.totalHits());
            searchHits = response.getHits();
            log.info("按日志号查询共匹配到记录条目:{}",searchHits.totalHits());
            for(SearchHit hit:searchHits){
                log.info("按日志号查询:{}"+hit.getSourceAsString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public  void add() throws UnknownHostException {
        JSONObject json = new JSONObject();
        json.put("a","11111111111");
        json.put("b","22222222");
        json.put("c","3333333");
        getClient().prepareIndex("blog", "article")
                .setSource(json)
                .setId(UUID.randomUUID().toString())//自己设置了id，也可以使用ES自带的，但是看文档说，ES的会因为删除id发生变动。
                .execute()
                .actionGet();

    }

    public static SearchResponse search(String index,String match,String path,int size ) throws UnknownHostException {

        BoolQueryBuilder queryBuilder =    QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("message", match));
        if(path != null ){
            queryBuilder.must(QueryBuilders.matchPhraseQuery("path", path));
        }

        SearchResponse response = getClient().prepareSearch(index)
                .setQuery(queryBuilder)
                .setSize(size)
                .addSort("@timestamp", SortOrder.ASC)
                .execute().actionGet();

        return response;
    }

    public static TransportClient getClient() throws UnknownHostException {
        String serverUrl = "";
        serverUrl = "120.132.8.173";
       // serverUrl = "139.224.226.206";
        //设置集群名称
        Settings settings = Settings.builder().put("cluster.name", "es-cluster").build();
        //创建client
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(serverUrl), 9300));

        return client;
    }

    //提取日志ID
    public static String getTraceLogId(String message){
        Pattern p=Pattern.compile("\\[([^\\[\\]]+)\\]");
        Matcher m=p.matcher(message);
        int index = 0;
        String traceLogId ;
        while (m.find()){
            if(index == 2){
                traceLogId = m.group(1);
                log.info("提取到traceLogId：{}",traceLogId);
                return  traceLogId;
            }
            index++;
        }
        log.warn("未提取到traceLogId，请检查日志格式是否正确");
        return null;
    }
}
